<template>
    <div class="version-body" :style="{ transform: firstShow && show ? 'translateX(0)' : '' }"
        :class="[isShowArrow && 'version-body-fixed']" v-click-outside="onClickBodyOut">
        <div class="version-tilte">
            <div class="name">
                <span>{{ $t('message.text.version') }}</span>
                <svg class="hidden-icon" v-if="isShowArrow" @click="showArrowButton">
                    <use xlink:href="#keowledge-shousuo"></use>
                </svg>
            </div>
            <svg class="close-icon" @click="closeVersion">
                <use xlink:href="#keowledge-danchuangguanbi1"></use>
            </svg>
        </div>
        <div class="version-content">
            <el-scrollbar ref="versionScrollRef">
                <div v-for="(item, index) in versionList" :key="index" class="version-item">
                    <div class="version-item-title">
                        <svg class="arrow-icon" @click="openCurrentItem(item)">
                            <use
                                v-bind:xlink:href="`#${!item.isOpen ? 'keowledge-xiala-shouqi' : 'keowledge-xiala-zhankai'}`">
                            </use>
                        </svg>
                        <span class="name">{{ item.groupTime }}</span>
                    </div>
                    <div class="version-item-body" :class="[item.isOpen ? 'version-item-open' : '']">
                        <div class="version-items">
                            <div class="version-item" v-for="(cItem, cIndex) in item.list" :key="cIndex">
                                <div class="version-num">
                                    <div class="left">
                                        <div>{{ filterTime(cItem.versionNumber) }}</div>
                                        <div class="crrent-version" v-if="cItem.isCurrent">
                                            {{ $t('message.text.currentVersion') }}</div>
                                    </div>
                                    <div class="version-more"
                                        :class="[curOpenPop.versionNumber == cItem.versionNumber && 'version-more-active']"
                                        :ref="(el) => setRefObj(el, cItem)" @click="openPop(cItem, index, cIndex)">
                                        <i class="knowledge-iconfont keowledge-gengduocaozuo "></i>
                                    </div>
                                </div>
                                <div class="version-user">
                                    <img :src="cItem.userDto.headImg ? cItem.userDto.headImg : userImg">
                                    <span>{{ cItem.userDto.realName }}</span>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </el-scrollbar>
        </div>
        <el-popover ref="popoverRef" :virtual-ref="versionMoreRef" trigger="click" virtual-triggering
            :visible="morePopover" placement="bottom-start" popper-class="version-more-popover">
            <div class="more-action-box" v-click-outside="onClickOutside">
                <div class="action-item" @click="doAction('switch')">
                    <svg class="icon">
                        <use xlink:href="#keowledge-qiehuan"></use>
                    </svg>
                    <span>{{ $t('message.buttons.switch') }}</span>
                </div>
                <div class="action-item" @click="doAction('del')">
                    <svg class="icon">
                        <use xlink:href="#keowledge-huishouzhan-weixuanzhong"></use>
                    </svg>
                    <span>{{ $t('message.buttons.delete') }}</span>
                </div>
            </div>
        </el-popover>
    </div>
</template>

<script setup lang="ts">
import {
    ref,
    reactive,
    toRefs,
    watch,
    onMounted,
    nextTick,
    getCurrentInstance
} from 'vue'
import type { ComponentInternalInstance } from 'vue'
import { useRouter } from "vue-router"
import { versionPage, versionBack, versionDel, getByIdVersionContent } from '@/api/version'
import userImg from '@/assets/common/img/user.png'
import { ClickOutside as vClickOutside } from 'element-plus'
import { useHookI18n } from '@/hooks/i18n'
const { locale, $t } = useHookI18n()
const router = useRouter();
const instance: any = getCurrentInstance() as ComponentInternalInstance;
const proxy: any = instance.proxy as any; // 访问 proxy 属性
const emit = defineEmits(["close", "changeArrow", 'endSwitchVersion'])
const props = defineProps({
    docId: {
        type: String,
        default: ''
    },
    show: {
        type: Boolean,
        default: false
    },
    isShowArrow: {
        type: Boolean,
        default: false
    }
})
const firstShow = ref(false)
const versionList = ref([])
const versionScrollRef = ref()
const refObj = ref({})
const curOpenPop = ref({})
const popoverRef = ref()
const versionMoreRef = ref()
const morePopover = ref(false)
const popverIndex = ref(0)
const popverListIndex = ref(0)
watch(() => props.docId, (newV) => {
    if (newV) {
        getVersionAll()
    }
})
onMounted(() => {
    if (props.docId) {
        getVersionAll()
    }
    nextTick(() => {
        firstShow.value = true
    })
})
function setRefObj(el, data) {
    if (el) {
        refObj.value[data.versionNumber] = el
    }
}
function getVersionAll() {
    curOpenPop.value = {}
    versionList.value = []
    versionPage({ id: props.docId }).then(res => {
        if (res.data.code == 0) {
            let data = res.data.data
            let newList = []
            for (let key in data) {
                newList.push({
                    groupTime: key,
                    isOpen: false,
                    itemOpen: false,
                    list: data[key],
                })
            }
            versionList.value = newList.sort((a, b) => {
                return new Date(b.groupTime).getTime() - new Date(a.groupTime).getTime()
            })
        }
    })
}
function filterTime(val) {
    return proxy.$dayjs(val).format('MM.DD HH:mm')
}
function openCurrentItem(item) {
    item.isOpen = !item.isOpen
}
function openPop(item, index, cIndex) {
    popverIndex.value = index
    popverListIndex.value = cIndex
    curOpenPop.value = item
    versionMoreRef.value = refObj.value[item.versionNumber]
    morePopover.value = true
}
function onClickOutside() {
    popverIndex.value = 0
    popverListIndex.value = 0
    // curOpenPop.value = {}
    morePopover.value = false
    versionMoreRef.value = null
}
function doAction(type: string) {
    switch (type) {
        case 'switch':
            proxy.$confirm(`${$t('message.message.switchVersionFirst')}${filterTime(curOpenPop.value.versionNumber)}${$t('message.message.switchVersionEnd')}`, $t('message.prompt'), {
                confirmButtonText: $t('message.buttons.switch'),
                cancelButtonText: $t('message.buttons.cancal')
            }).then(() => {
                if (curOpenPop.value.mongodbContent) {
                    versionBack(curOpenPop.value).then(res => {
                        if (res.data.code == 0) {
                            versionList.value.forEach(item => {
                                item.list.forEach(items => {
                                    items.isCurrent = false
                                })
                            })
                            curOpenPop.value.isCurrent = true
                            emit('endSwitchVersion', curOpenPop.value.mongodbContent._data, 'version')
                        }
                    })
                } else {
                    getByIdVersionContent(curOpenPop.value.id).then(res => {
                        if (res.data.code == 0) {
                            versionList.value.forEach(item => {
                                item.list.forEach(items => {
                                    items.isCurrent = false
                                })
                            })
                            curOpenPop.value.isCurrent = true
                            emit('endSwitchVersion', res.data.data.content, 'handleVersion')
                        }
                    })
                }
            }).catch(() => {
            });
            break;
        case 'del':
            proxy.$confirm($t('message.confirm.delVersion'), $t('message.prompt'), {
                confirmButtonText: $t('message.buttons.submit'),
                cancelButtonText: $t('message.buttons.cancal'),
                type: 'warning'
            }).then(() => {
                versionDel({ id: curOpenPop.value.id }).then(res => {
                    if (res.data.code == 0) {
                        versionList.value[popverIndex.value].list.splice(popverListIndex.value, 1)
                    }
                })
            }).catch(() => {
            });
            break
        default:
            break;
    }
}
function closeVersion() {
    emit("close")
}
function showArrowButton() {
    emit('changeArrow', true)
}
function onClickBodyOut() {
    if (props.isShowArrow) {
        showArrowButton()
    }
}
</script>
<style lang="scss" scoped>
.version-body {
    min-width: 240px;
    width: 240px;
    background-color: #fff;
    border-left: 1px solid #EEEFF0;
    padding: 16px 0px;
    height: 100%;
    transition: transform .2s;
    transform: translateX(100%);

    .version-tilte {
        padding-bottom: 16px;
        margin: 0px 16px;
        display: flex;
        align-items: center;
        justify-content: space-between;
        border-bottom: 1px solid #EEEFF0;

        .name {
            display: flex;
            align-items: center;
            font-size: 16px;
            color: #363b4c;

            span {
                @include SourceHanSansCN-Bold;
            }

            .hidden-icon {
                width: 16px;
                height: 16px;
                cursor: pointer;
            }
        }

        .close-icon {
            width: 16px;
            height: 16px;
            cursor: pointer;
        }
    }

    .version-content {
        height: calc(100% - 26px);
        background-color: #fff;

        .version-item {
            .version-item-title {
                padding: 8px 16px;
                display: flex;
                align-items: center;

                .arrow-icon {
                    width: 14px;
                    height: 14px;
                    cursor: pointer;
                    margin-right: 4px;
                }

                .name {
                    color: #363b4c;
                    font-size: 14px;
                    @include SourceHanSansCN-Medium;
                }
            }

            .version-item-body {
                margin: 0px 16px;
                background: #F5F6F7;
                border-radius: 4px 4px 4px 4px;
                display: grid;
                flex-direction: column;
                grid-template-rows: 0fr;
                overflow: hidden;
                transition: all 0.4s;

                .version-items {
                    overflow: hidden;

                    .version-item {
                        padding: 0px 12px 8px;

                        .version-num {
                            display: flex;
                            align-items: center;
                            justify-content: space-between;
                            padding: 8px 0px;

                            .left {
                                display: flex;
                                align-items: center;

                                .crrent-version {
                                    height: 20px;
                                    background: #EDF4FF;
                                    border-radius: 4px 4px 4px 4px;
                                    color: #1e6fff;
                                    font-size: 12px;
                                    line-height: 20px;
                                    padding: 0px 4px;
                                    margin-left: 8px;
                                }
                            }

                            .version-more {
                                width: 20px;
                                height: 20px;
                                display: flex;
                                align-items: center;
                                cursor: pointer;
                                border-radius: 4px 4px 4px 4px;
                                background-color: transparent;

                                &:hover {
                                    background-color: #E4EDFF;

                                    .keowledge-gengduocaozuo {
                                        color: #1E6FFF;
                                    }
                                }

                                .keowledge-gengduocaozuo {
                                    float: right;
                                    font-size: 20px;
                                    color: #C2C5CF;
                                }
                            }

                            .version-more-active {
                                background-color: #E4EDFF;

                                .keowledge-gengduocaozuo {
                                    color: #1E6FFF;
                                }
                            }
                        }

                        .version-user {
                            display: flex;
                            align-items: center;

                            img {
                                overflow: hidden;
                                width: 16px;
                                height: 16px;
                                border-radius: 4px 4px 4px 4px;
                            }

                            span {
                                color: #363b4c;
                                font-size: 14px;
                                margin-left: 8px;
                            }
                        }
                    }

                    .version-item+.version-item {
                        border-top: 1px solid #fff;
                    }
                }
            }

            .version-item-open {
                grid-template-rows: 1fr;
            }
        }
    }
}

.version-body-fixed {
    position: fixed;
    right: 0;
    z-index: 200;
    box-shadow: 0px 1px 10px 0px rgba(54, 59, 76, 0.15);
}
</style>
<style lang="scss">
.version-more-popover {
    width: 120px !important;
    min-width: 100px !important;
    padding: 8px !important;

    .more-action-box {
        .action-item {
            cursor: pointer;
            height: 32px;
            padding: 0px 8px;
            display: flex;
            align-items: center;
            border-radius: 4px;
            color: #363B4C;

            &:hover {
                background-color: #F5F6F7;
            }

            .icon {
                width: 16px;
                height: 16px;
                margin-right: 4px;
            }
        }
    }
}
</style>